package cn.iocoder.yudao.module.promotion.newcustomer.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.annotation.AdminJsonView;
import cn.iocoder.yudao.framework.business.basic.controller.PageController;
import cn.iocoder.yudao.framework.business.basic.controller.SimpleDetailController;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.ShopSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.module.api.promotion.gift.dto.GiftActivityVO;
import cn.iocoder.yudao.module.api.promotion.newcustomer.vo.NewCustomerConfigVO;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.promotion.gift.service.admin.GiftActivityService;
import cn.iocoder.yudao.module.promotion.newcustomer.convert.NewcustomerConfigConvert;
import cn.iocoder.yudao.module.promotion.newcustomer.pojo.dto.NewcustomerConfigQueryDTO;
import cn.iocoder.yudao.module.promotion.newcustomer.pojo.dto.NewcustomerConfigSaveDTO;
import cn.iocoder.yudao.module.promotion.newcustomer.pojo.po.NewcustomerConfig;
import cn.iocoder.yudao.module.promotion.newcustomer.service.admin.NewcustomerConfigService;
import cn.iocoder.yudao.module.promotion.newcustomer.service.core.CoreNewcustomerConfigService;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 前端控制器
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/07/11
 */
@Tag(name = "管理后台 - 新客优惠配置")
@RestController
@RequestMapping("/promotion/newcustomer/config")
public class NewcustomerConfigController implements SimpleDetailController<NewCustomerConfigVO>, PageController<NewCustomerConfigVO, NewcustomerConfigQueryDTO> {
    @Resource
    private NewcustomerConfigService newcustomerConfigService;
    @Resource
    private CoreNewcustomerConfigService coreNewcustomerConfigService;
    @Resource
    private GiftActivityService giftActivityService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    @JsonView(AdminJsonView.class)
    @Override
    public CommonResult<NewCustomerConfigVO> getDetail(Long id) {
        NewCustomerConfigVO data = newcustomerConfigService.getDetail(id);
        return CommonResult.success(data);
    }

    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    @JsonView(AdminJsonView.class)
    @Override
    public CommonResult<PageResult<NewCustomerConfigVO>> getPage(Integer pageNo, Integer pageSize, NewcustomerConfigQueryDTO param) {
        PageResult<NewCustomerConfigVO> page = newcustomerConfigService.getPage(pageNo, pageSize, param);
        Set<Long> shopIds = convertSet(page.getList(), NewCustomerConfigVO::getShopId);
        Map<Long, ShopSimpleVO> shops = shopInfoApi.getShopSimpleMap(shopIds);
        page.getList().forEach(vo -> vo.setShop(shops.getOrDefault(vo.getShopId(), ShopSimpleVO.EMPTY)));
        return CommonResult.success(page);
    }

    @GetMapping("/read")
    @Operation(summary = "读取配置内容")
    @PreAuthorize("@ss.hasRole('shop_admin')")
    @JsonView(AdminJsonView.class)
    public CommonResult<NewCustomerConfigVO> read() {
        Long shopId = shopInfoApi.getShopIdByAdminUserId(getLoginUserId());
        NewcustomerConfig config = coreNewcustomerConfigService.getOrCreate(shopId);
        NewCustomerConfigVO data = NewcustomerConfigConvert.INSTANCE.toViewObject(config);
        // 获取别的商家的赠品活动，需要忽略店铺数据权限
        List<GiftActivityVO> list = DataPermissionUtils.executeIgnore(() -> giftActivityService.getList(data.getGiftActivityIds()));
        if (CollUtil.isNotEmpty(list)) {
            data.setGiftActivityNames(list.stream()
                    .map(GiftActivityVO::getName)
                    .filter(Objects::nonNull)
                    .toList());
        }
        return CommonResult.success(data);
    }

    @PostMapping("/write")
    @Operation(summary = "写入配置内容")
    @PreAuthorize("@ss.hasRole('shop_admin')")
    public CommonResult<Boolean> write(@RequestBody @Valid NewcustomerConfigSaveDTO param) {
        Long shopId = shopInfoApi.getShopIdByAdminUserId(getLoginUserId());
        return CommonResult.success(newcustomerConfigService.save(shopId, param));
    }


}
